package com.amt.util;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title: IdCardUtil.java 
 * @Package com.amt.util 
 * @Description: TODO(解析身份证) 
 * @author 江伟  
 * @date 2020年3月5日 下午3:20:20 
 * Copyright (c) ©1994-2021 Scjydz.com All Rights Reserved.
 */
public class IdCardUtil {


    /**
     * 获取年龄
     * @param idCard
     * @return
     */
    public static Integer getAge(String idCard){
        if (StringUtil.isNotEmpty(idCard)){
            String year = idCard.substring(6, 10);
            Calendar cal = Calendar.getInstance();
            int iCurrYear = cal.get(Calendar.YEAR);
            return iCurrYear - Integer.valueOf(year);
        }
        return 0;
    }


    /**
     * 生日
     * @param idCard
     * @return
     */
    public static String getBirthday(String idCard){
        String year = idCard.substring(6,10);
        String month = idCard.substring(10,12);
        String day = idCard.substring(12,14);
        String birthday=year+"-"+month+"-"+day;
        return birthday;
    }

    /**
     * 获取性别(1: 男, 2:女：0未知)
     * @param idCard
     * @return
     */
    public static Integer getGender(String idCard){
        Integer gender = 0;
        if (idCard.length() == 18) {
            idCard = idCard.substring(16, 17);
        }else if (idCard.length() == 15 ) {
            idCard = idCard.substring(13,14);
        }
        if (Integer.parseInt(idCard) % 2 != 0) {
            gender = 1;
        }else {
            gender = 2;
        }
        return gender;
    }

    /**
     * 身份证隐藏出生年月日
     * @param idCard
     * @return
     */
    public static String idCardConvert(String idCard){
        if (null != idCard && idCard.length() > 0){
            Pattern p = Pattern.compile("(\\w{1})(\\w+)(\\w{1})");
            Matcher m = p.matcher(idCard);
            return m.replaceAll("$1****************$3");
        }
        return "";
    }

    /**
     * 身份证  正则校验 简单版
     * @param idCard
     * @return
     */
    public static boolean idCardCheck(String idCard){

        String id_18="^[1-9][0-9]{5}(18|19|20)[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}([0-9]|(X|x))";

        String id_15="^[1-9][0-9]{5}[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{2}[0-9]";

        String id_valid="("+id_18+")"+"|"+"("+id_15+")";

        if (null != idCard ){
            return idCard.matches(id_valid);
        }
        return false;
    }

}
